const multer = require('multer');
const fs = require('fs');

//创建文件夹（上传文件的文件夹）
function createDir(pathJion, n = 0) {
    //'public/upload/2022/8/31/'
    const res = pathJion.indexOf('/', n) + 1;
    //判断文件夹是否已创建
    try {
        //fs.statSync(path,cb) 同步模式获取文件信息
        fs.statSync(pathJion.slice(0, res));
    } catch (err) {
        //fs.mkdirSync(path,option,cb) 创建目录
        fs.mkdirSync(pathJion.slice(0, res));
    }
    if (res < pathJion.length) {
        createDir(pathJion, res);
    }
}

//storage（内存存储）动态上传
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        const data = new Date();
        let pathJion = 'public/upload/';
        pathJion += data.getFullYear() + '/';
        pathJion += data.getMonth() + 1 + '/';
        pathJion += data.getDate() + '/';
        //创建目录
        createDir(pathJion);
        cb(null, pathJion);

    },
    //生成文件名（图片名称）
    filename: function (req, file, cb) {
        //获取图片后缀名拼接
        let pathSuffix = file.originalname;
        pathSuffix = pathSuffix.slice(pathSuffix.lastIndexOf('.'));
        //与时间戳拼接
        pathSuffix = new Date().getTime() + pathSuffix;
        //再与随机数拼接，最后生成文件名称
        pathSuffix = Math.floor(Math.random() * 1E9) + '-' + pathSuffix;
        cb(null, pathSuffix);
    }
})
//实例化
const upload = multer({ storage: storage });
module.exports = upload